package com.hotel.homehotel.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotel.homehotel.before.entiy.User;
import com.hotel.homehotel.before.entiy.vo.UserVo;
import com.hotel.homehotel.before.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import com.alibaba.fastjson.JSON;

/**
 * 自定义认证成功处理器
 */

@Component
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JwtTokenUtil jwtTokenUtil;
   @Resource
    UserMapper  userMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //生成token
        System.out.println("1111111111111");

        System.out.println("22222222222222222");

        final String realToken = jwtTokenUtil.generateToken(authentication.getName());
        //将生成的authentication放入容器中，生成安全的上下文
        SecurityContextHolder.getContext().setAuthentication(authentication);
        QueryWrapper queryWrapper =new QueryWrapper();
        queryWrapper.eq("phone_Number",authentication.getName());
        User user = userMapper.selectOne(queryWrapper);
        UserVo userVo = ConversionUtils.toUserVo(user);
        String json = JSON.toJSONString(R.define(true, 200, "登录成功").data("token", realToken).data("user",userVo));
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write(json);
    }
}
